package com.zhende.hr.config;

import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, org.springframework.security.access.AccessDeniedException accessDeniedException) throws IOException {
        System.out.println("进入了 CustomAccessDeniedHandler.handle() 方法");

    	//response.setStatus(HttpServletResponse.SC_FORBIDDEN);  // 设置状态码为 403
        response.setContentType("application/json;charset=UTF-8");  // 设置响应类型为 JSON，并指定 UTF-8 编码

        // 创建自定义的错误响应格式
        String jsonResponse = String.format(
            "{ \"timestamp\": \"%s\", \"code\": %d, \"error\": \"%s\", \"msg\": \"%s\", \"path\": \"%s\" }",
            LocalDateTime.now(),  // 当前时间戳
            HttpServletResponse.SC_FORBIDDEN,  // 状态码 403
            "Forbidden",  // 错误类型
            "Access Denied",  // 错误信息
            request.getRequestURI()  // 请求路径
        );

        // 写入响应内容
        response.getWriter().write(jsonResponse);
    }
}
